package main.java.indi.zyj.hot100;

public class _73_findKthLargest {

    public int findKthLargest(int[] nums, int k) {
        int len = nums.length;
        buildMaxHeap(nums, len);
        for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {
            swap(nums, 0, i);
            --len;
            AdjustMaxHeap(nums, 0, len);
        }
        return nums[0];
    }

    private void buildMaxHeap(int[] nums, int len) {
        for (int i = len / 2; i >= 0 ; i--) {
            AdjustMaxHeap(nums, i, len);
        }
    }

    private void AdjustMaxHeap(int[] nums, int i, int len) {
        int l = i * 2 + 1, r = i * 2 + 2, largest = i;
        if (l < len && nums[l] > nums[largest]) {
            largest = l;
        }
        if (r < len && nums[r] > nums[largest]) {
            largest = r;
        }
        if (largest != i) {
            swap(nums, i, largest);
            AdjustMaxHeap(nums, largest, len);
        }
    }

    public void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
